import { observable, action, toJS } from "mobx";
import { WeaTools, WeaLocaleProvider } from "ecCom";
import { WeaForm, } from "comsMobx";
import * as Api from "../../apis/receiveDoc";
import CommonStore from "../commonStore";
import * as conditions from "../../constants/conditions";
import { message } from "antd";

const { getLabel } = WeaLocaleProvider;
export default class ReceiveDoc extends CommonStore {
  test = "接收公文";

  constructor() {
    super();
    this.pageName = "receiveDoc";
  }
  @observable menuType = "receiveDoc";

  @observable ifShowRejectForm = false;//拒收弹窗显隐
  @observable rejectForm = new WeaForm();
  @observable rejectFormCon = conditions.rejectCondt;

  @observable ifSendBackForm = false;//退回弹窗的显隐
  @observable sendBackForm = new WeaForm();
  @observable sendBackFormCon = conditions.sendBackCondt;

  /*
   *配置流程相关store
   */
  @observable setWfDiaForm = new WeaForm();
  @observable setWfDiaFormCon = "";
  @observable tableEditTitle = "";
  @observable tableEditCols = [];
  @observable tableEditDatas = [];

  //这几个加上setWfDiaForm可用于获取tableedit的cols和datas
  @observable chageFlag = "";
  @observable companyid = "";
  @observable sn = "";
  @observable ifShowSetWFDia = false;
  @observable ifShowTableEdit = false; //这个表示是否显示配置流程弹窗里的tableedit组件，仅在刚点击配置按钮后且并没有改动表单中任何值的时候才为false
  @observable ifShowLoadingAnimation = false; //表示配置流程弹窗中是否出现一个loading动画————一个用于表示loading新的tableedit的动画
  @observable createWorkflowLoading = false;
  /**
   * 创建流程store
   */
  @observable selTableIdOfcreateWF = "";
  @observable createWFsn = "";
  @observable createWfid = "";

  //创建流程弹窗
  @observable showCreatFlow = false;
  @observable selectRowId = [];//选择行的Id
  @observable flowListData = [];//流程列表数据
  @observable isInnerChange = 0;

  //流程列表数据
  @action.bound getFlowList(officalType) {
    const params = { officalType, isInnerChange: this.isInnerChange }
    Api.createChangeFlowList(params).then(data => {
      if (data.api_status) {
        if (toJS(this.flowListData).length == 0 && data.datas[0]) {
          this.flowListData = data.datas
        } else {
          if (data.datas[0]) {
            let tempData = [];
            data.datas.forEach(list => {
              this.flowListData.map(item => {
                if (item.id == list.id) {
                  item.wfbeans = [...item.wfbeans, ...list.wfbeans];
                  item.wfCount = item.wfCount + list.wfCount;
                } else {
                  tempData.push(list)
                }
              })
            })
            this.flowListData = this.flowListData.concat(tempData)
          }
        }
      }

    })
  }
  //新建流程
  @action.bound openCreatFlowWindow(workflowid) {
    if (this.createWorkflowLoading) {
      return;
    }
    this.createWorkflowLoading = true;
    const params = {
      ids: this.selectRowId.join(","),
      createWfid: workflowid,
      isInnerChange: this.isInnerChange
    }

    Api.getRequstId(params).then(data => {
      this.createWorkflowLoading = false;
      if (data.status) {
        if (this.menuType != "receiveDoc") {
          var formData = this.handworkForm.getFormParams();
          formData.Document_Attachments = this.fileId.Document_Attachments;
          formData.Document_Text = this.fileId.Document_Text;
          this.initData({
            compParams: {
              viewcondition: 0,
              viewconditiondomkey: "state",
              menuType: this.menuType,
              isInnerChange: this.isInnerChange,
              state: 0
            }
          });
        }
        const width = screen.availWidth - 10;
        const height = screen.availHeight - 50;
        let szFeatures = "top=0,left=0,";
        szFeatures += "width=" + width + ",";
        szFeatures += "height=" + height + ",";
        szFeatures += "directories=no,status=yes,toolbar=no,location=no,";
        szFeatures += "menubar=no,scrollbars=yes,resizable=yes";
        this.eleRegistShowOnCancel();
        this.createWorkflowOnCancel();
        window.open(data.url, "", szFeatures);
        this.showCreatFlow = false
      } else {
        message.error(data.message);
      }
    }).catch(error => {
      message.error(error)
    })
  }

  //获取页面类型 并初始化页面
  @action.bound getMenuType(menuType) {
    if (menuType) {
      this.menuType = menuType;
      this.initData({
        compParams: {
          viewcondition: 0,
          viewconditiondomkey: "state",
          menuType: menuType,
          isInnerChange: this.isInnerChange,
          state: 0
        }
      });

    } else {
      Api.getMenuType().then(data => {
        this.menuType = data.menuType;
        // this.menuType = "receiptRegistration";
        this.initData({
          compParams: {
            viewcondition: 0,
            viewconditiondomkey: "state",
            menuType: this.menuType,
            isInnerChange: this.isInnerChange,
            state: 0
          }
        });
      })
    }
  }



  /*------------------------------- 收文登记-------------------*/

  //手工登记 
  @observable handworkForm = new WeaForm();//手工登记form
  @observable handwordCondition = [];
  @observable handworkShow = false;

  @observable registDailogKey = "0";

  @observable eleRegistShow = false;

  @observable registProcessShow = false; //登记处理
  @observable fileId = {} //文件id
  @observable fileInfoArr = {
    Document_Attachments: [],
    Document_Text: [],
  } //文件信息

  @observable docId = "";
  @observable step = "1";
  @observable type = "1"; //type  0 代表手工登记的二级弹窗 1 智能登记二级弹窗 2 扫码登记 

  //创建流程
  @observable createWorkflowDialog = false;
  @observable tabs = [];
  @observable workflowData = [];
  @observable workflowKeys = "0"

  //登记处理
  @observable receiveSmartShow = false;

  @observable isReceivecheck = false;
  @observable document_identifier = "";
  @observable isShowAllTab = false;
  isReally = false;

  @action.bound setMobxState(params = {}) {
    Object.keys(params).forEach(v => {
      this[v] = params[v]
    })
  }

  //处理手工登记form表单
  @action.bound setRegistrationForm(data) {
    this.handworkForm = new WeaForm();
    let file = [];
    const items = data.condition[0].items
    for (let i = 0; i < data.condition[0].items.length; i++) {
      const item = items[i];
      if (item.conditionType.toUpperCase() == WeaTools.types.UPLOAD) {
        this.fileInfoArr[item.domkey[0]] = item.datas || [];
      }
      //为了美观 把附件放在最后
      if (item.domkey[0] == "Document_Attachments") {
        items.splice(i, 1)
        file.push(item);
        i--;
      }
      //为了美观 把正文放在最后
      if (item.domkey[0] == "Document_Text") {
        items.splice(i, 1)
        file.unshift(item);
        i--;
      }
    }
    data.condition[0].items = [...data.condition[0].items, ...file]
    this.handworkForm.initFormFields(toJS(data.condition));
    this.handwordCondition = data.condition;
  }

  //登记保存
  @action.bound
  registSave(CreatFlow) {

    let formData = this.handworkForm.getFormParams();
    if (this.fileId.Document_Text) {
      formData.Document_Attachments = this.fileId.Document_Attachments;
      formData.Document_Text = this.fileId.Document_Text;
    }
    if (formData.Document_Title == '' || formData.Document_Text == "") {
      message.warning(getLabel('', '你有必填项没有填'))
      return;
    }
    const params = {
      ...formData,
      receiveDocType: this.registDailogKey,
      receiveStatus: "0",
      documentIdentifier: this.document_identifier,
    }
    this.loading = true;
    Api.saveRegistrationFormData(params).then(data => {
      this.loading = false;
      if (data.api_status) {
        //获取id 为创建流程所用
        this.initData({
          compParams: {
            viewcondition: 0,
            viewconditiondomkey: "state",
            menuType: this.menuType,
          }
        });
        if (CreatFlow) {
          if (data.message) {
            this.selectRowId = [data.message];
          }
          this.document_identifier = data.documentIdentifier;
          this.createWorkflowDialog = true;
          return;
        } else {
          this.eleRegistShowOnCancel();
        }
      } else {
        message.warning(data.message)
      }
    })
  }

  //智能登记的时候显示上传文件信息
  @action.bound setFileInfo(type, ids, list, name) {
    this.fileId[type] = ids.join(",");
    this.fileInfoArr[type] = list;
    if (name == "smartRegist") {
      let nameArr = [];
      list.map(item => {
        nameArr.push(item.filename)
      })
    }
    if (this.registDailogKey == '3') {
      if (toJS(this.fileInfoArr.Document_Text)[0] && toJS(this.fileInfoArr.Document_Text)[0].fileExtendName != "pdf") {
        this.getChangeWordToPdf();
      }
    }

  }

  //智能登记 下一步
  @action.bound smartRegistration() {

    const imageFileNameArr = toJS(this.fileInfoArr.Document_Text).map(item => item.filename);
    const imageFileName = imageFileNameArr.join(',');
    this.loading = true;
    const params = {
      docType: this.registDailogKey,
      imageFileId: this.fileId.Document_Text,
      imageFileName: imageFileName,
      attachmentIds: this.fileId.Document_Attachments,
      isReally: this.isReally ? "0" : "1" // 返回的数据 真 或 假 1假 0真
    }
    Api.smartRegistration(params).then(data => {
      this.loading = false;
      if (data.api_status) {
        this.docId = data.imagefileid;
        this.setRegistrationForm(data)
        this.step = '2';
      } else {
        this.dialogOnCancel()
        message.error(getLabel("", "文件转换失败"))
      }
    })
  }

  @action.bound secondDialogOncCancel() {
    this.registProcessShow = false;
    this.clearFile()
    this.isReceivecheck = false;
    this.selectRowId = [];
  }

  //点击查看
  @action.bound
  getRegistrationFormData() {
    const params = {
      id: this.selectRowId.join(",")
    }
    Api.getRegistrationFormData(params).then(data => {
      if (data.api_status) {
        this.setRegistrationForm(data)
        this.docId = data.message;
        this.eleRegistShow = true;
        this.step = "2";
        this.type = "0";
      }
    })
  }

  //收文登记
  @action.bound
  delList(id) {
    const params = {
      ids: id
    }
    Api.delList(params).then(data => {
      if (data.api_status) {
        this.selectRowId = []
        message.success(getLabel('', '删除成功'));
        this.initData({
          compParams: {
            viewcondition: 0,
            viewconditiondomkey: "state",
            menuType: this.menuType,
          }
        });
      }
    })
  }

  //登记处理
  @action.bound
  nextTept() {
    this.handworkForm.validate().then(f => {
      if (f.isValid) {
        this.type = "0";
        this.step = "2";
        if (this.fileInfoArr.Document_Text[0].fileExtendName != "pdf") {
          this.getChangeWordToPdf();
        }
      } else {
        f.showErrors();
      }
    })
  }

  //上一步
  @action.bound
  previousTept() {
    this.step = "1";
    this.clearFile()
  }

  //手工登记关闭
  @action.bound
  handwordRegistOnCancel() {
    this.handworkShow = false;
    this.clearFile()
  }

  //电子登记关闭
  @action.bound
  eleRegistShowOnCancel() {
    this.eleRegistShow = false;
    this.step = "1";
    this.registDailogKey = "0";
    this.type = "1";
    this.clearFile();
    this.document_identifier = "";
    this.selectRowId = [];
    this.isReceivecheck = false;
  }

  //智能登记关闭
  @action.bound
  dialogOnCancel() {
    this.receiveSmartShow = false;
    this.clearFile()
  }

  //清除文件信息
  @action.bound
  clearFile() {
    this.fileId = {};
    this.fileInfoArr = {
      Document_Attachments: [],
      Document_Text: [],
    }
  }

  @action.bound
  getChangeWordToPdf() {
    const params = {
      imageFileId: this.fileId.Document_Text,
    }
    Api.changeWordToPdf(params).then(data => {
      if (data.api_status) {
        this.docId = data.message;
      } else {
        message.error(data.message)
      }
    })
  }

  @action.bound
  changeTab(v) {
    this.registDailogKey = v;
    this.clearFile();
    if (v == "0" || v == "1") {
      this.type = "1";
    } else if (v == "2") {
      this.type = '2';
      this.getHandForm();
    } else if (v == "3") {
      this.type = '0';
      this.getHandForm();
    }
  }

  @action.bound
  getBaseInfoForDemo() {
    Api.getBaseInfoForDemo().then(data => {
      this.tabs = data.groupinfo || [];
      this.getWorkflowListByTypeForDemo();
    })
  }

  @action.bound
  getWorkflowListByTypeForDemo() {
    let params = {}
    toJS(this.tabs).map(item => {
      if (item.viewcondition == this.workflowKeys) {
        params.groupid = item.groupid;
        params.title = item.title;
      }
    })
    Api.getWorkflowListByTypeForDemo(params).then(data => {
      if (data.api_status) {
        this.workflowData = data.data;
      }
    })
  }

  @action.bound
  changeWorkflowTab(v) {
    this.workflowKeys = v;
    this.getWorkflowListByTypeForDemo()
  }

  @action.bound
  createWorkflowOnCancel(cancel = false) {
    this.createWorkflowDialog = false;
    this.document_identifier = "";
    this.selectRowId = [];
    if (!cancel) {
      this.step = "1";
      this.eleRegistShowOnCancel();
    }
  }

  @action.bound
  getHandForm() {
    Api.getRegistrationForm().then(data => {
      this.setRegistrationForm(data)
    });
  }

  //点击来文登记按钮
  @action.bound
  showRegistDialog() {
    this.loading = true;
    Api.getRegistrationForm().then(data => {
      this.loading = false;
      this.setRegistrationForm(data)
      this.setMobxState({ eleRegistShow: !this.eleRegistShow, type: "1" })
      if (data.condition[0]) {
        this.isShowAllTab = data.condition[0].isShowAllTab == false ? false : true;
        this.registDailogKey = (!this.isShowAllTab && (this.registDailogKey == '0' || this.registDailogKey == '1')) ? '2' : '0';
        this.type = (!this.isShowAllTab && this.registDailogKey == '2') ? '2' : '1';
      }
    });
  }

  /*---------------------------------顶部操作菜单的方法------------------------------------*/
  //签收
  @action.bound
  onSigninDoc() {
    this.loading = true;
    const params = {
      ids: this.selectRowId.join(","),
      status: 1,
      isInnerChange: this.isInnerChange
    };
    Api.signinDoc(params).then(data => {
      this.getList(data);
    })
  }

  //刷新列表
  @action.bound
  getList(data) {
    this.loading = false;
    if (data.api_status) {
      message.success(getLabel("30700", "操作成功"));
    } else {
      message.error(data.api_message);
    }
    this.selectRowId = [];
    this.onSearch({ behavior: 'search' });
  }

  //接收
  @action.bound
  onReceive() {
    this.loading = true;
    const params = { isInnerChange: this.isInnerChange }
    Api.receiveDoc(params).then(data => {
      this.getList(data)
    });
  }

  //显示列定制
  @action.bound
  customSet() {
    this.tableStore.setColSetVisible(true);
    this.tableStore.tableColSet(true);
  }

  //搜索接口
  @action.bound
  onSearch({ behavior, viewcondition }) {
    this.doSearch({
      ifAdFormCgWhenCgTab: true,
      behavior: behavior,
      viewcondition: viewcondition || this.viewcondition,
      viewconditiondomkey: "state",
      otherInterfaceParams: {
        menuType: this.menuType,
        isInnerChange: this.isInnerChange,
        state: viewcondition || this.viewcondition
      }
    });
  }

  //退回
  @action.bound
  sendBack() {
    this.loading = true;
    const params = {
      ids: this.selectRowId.join(","),
      status: 3,
      isInnerChange: this.isInnerChange,
      ...this.sendBackForm.getFormParams()
    };
    Api.sendbackDoc(params).then(data => {
      this.sendBackForm.resetForm()
      this.getList(data)
      this.ifSendBackForm = false;
    });
  }

  //拒收
  @action.bound
  onReject() {
    const params = {
      ids: this.selectRowId.join(","),
      status: 3,
      isInnerChange: this.isInnerChange,
      ...this.rejectForm.getFormParams()
    };
    Api.rejectDoc(params).then(data => {
      this.rejectForm.resetForm()
      this.getList(data)
      this.ifShowRejectForm = false;
    });
  }

  @action.bound
  createFTPWF() {
    const params = {
      ids: this.selTableIdOfcreateWF,
      sn: this.createWFsn,
      createWfid: this.createWfid,
      isInnerChange: this.isInnerChange
    }
    Api.createworkflow(params).then(data => {
      const { status } = data;
      if (status) {
        message.success(data.message);
        window.open(data.url);
      } else {
        message.warn(data.message);
      }
    });

  }





}
